<template>
  <div class="app-container">
    <el-card>
      <div class="filter-container">
        <el-form :inline="true">
          <el-form-item label="药品名称">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入药品名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="药品类型">
            <el-input
              v-model="queryParams.type"
              placeholder="请输入药品类型"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain @click="handleAdd">新增药品</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="medicineList">
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="药品名称" prop="name" width="150" />
        <el-table-column label="药品类型" prop="type" width="120" />
        <el-table-column label="售价" width="120">
          <template #default="scope"> {{ (scope.row.price / 100).toFixed(2) }} 元 </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '在售' : '停售' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="成分说明" prop="ingredients" width="180" show-overflow-tooltip />
        <el-table-column label="用法用量" prop="usageInfo" width="180" show-overflow-tooltip />
        <el-table-column label="禁忌" prop="contraindication" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" v-model="open" width="600px" append-to-body>
        <el-form ref="medicineFormRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="药品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入药品名称" />
          </el-form-item>
          <el-form-item label="药品类型" prop="type">
            <el-input v-model="form.type" placeholder="请输入药品类型" />
          </el-form-item>
          <el-form-item label="售价(元)" prop="price">
            <el-input-number v-model="priceInYuan" :min="0" :precision="2" style="width: 100%" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="成分说明" prop="ingredients">
            <el-input v-model="form.ingredients" type="textarea" placeholder="请输入成分说明" />
          </el-form-item>
          <el-form-item label="用法用量" prop="usageInfo">
            <el-input v-model="form.usageInfo" type="textarea" placeholder="请输入用法用量" />
          </el-form-item>
          <el-form-item label="禁忌" prop="contraindication">
            <el-input v-model="form.contraindication" type="textarea" placeholder="请输入禁忌" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { listMedicine, getMedicine, addMedicine, updateMedicine, delMedicine } from '@/api/medicine'

// 遮罩层
const loading = ref(false)
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParams = ref({
  name: undefined,
  type: undefined,
  status: undefined
})

// 表单参数
const form = ref({
  id: undefined,
  name: undefined,
  type: undefined,
  ingredients: undefined,
  usageInfo: undefined,
  contraindication: undefined,
  price: 0,
  status: 0
})

// 价格转换（元）
const priceInYuan = computed({
  get: () => form.value.price / 100,
  set: (val) => (form.value.price = Math.round(val * 100))
})

// 表单校验
const rules = {
  name: [{ required: true, message: '药品名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '药品类型不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '售价不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
}

// 状态选项
const statusOptions = [
  { value: 0, label: '在售' },
  { value: 1, label: '停售' }
]

const medicineFormRef = ref()
const medicineList = ref([])

/** 查询药品列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await listMedicine(queryParams.value)
    medicineList.value = res
    loading.value = false
  } catch (error) {
    loading.value = false
    console.error(error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    name: undefined,
    type: undefined,
    status: undefined
  }
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加药品'
}

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset()
  const id = row.id
  getMedicine(id).then((response) => {
    Object.assign(form.value, response)
    open.value = true
    title.value = '修改药品'
  })
}

/** 提交按钮 */
const submitForm = () => {
  medicineFormRef.value.validate((valid) => {
    if (valid) {
      if (form.value.id) {
        updateMedicine(form.value).then((response) => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addMedicine(form.value).then((response) => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  const id = row.id
  ElMessageBox.confirm('是否确认删除该药品?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(function () {
      return delMedicine(id)
    })
    .then(() => {
      getList()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    name: undefined,
    type: undefined,
    ingredients: undefined,
    usageInfo: undefined,
    contraindication: undefined,
    price: 0,
    status: 0
  }
}

/** 取消按钮 */
const cancel = () => {
  open.value = false
  reset()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
